package com.example.myapplication.ui.screens

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material3.*
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.example.myapplication.R
import com.example.myapplication.ui.components.StorageSpaceCard
import com.example.myapplication.ui.components.AddStorageSpaceDialog
import com.example.myapplication.ui.components.LoadingState
import com.example.myapplication.ui.components.ErrorState
import com.example.myapplication.ui.components.EmptyState
import com.example.myapplication.ui.components.ErrorSnackbar
import com.example.myapplication.ui.components.ActionBottomSheet
import com.example.myapplication.ui.components.ActionItem
import com.example.myapplication.data.model.StorageSpace
import com.example.myapplication.data.database.toModel
import com.example.myapplication.viewmodel.MainViewModel

/**
 * 主界面 - 显示顶级储物空间的块状网格
 */
@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
@Composable
fun MainScreen(
    onNavigateToStorageDetail: (String) -> Unit,
    onNavigateToSearch: () -> Unit,
    viewModel: MainViewModel = hiltViewModel()
) {
    val uiState by viewModel.uiState.collectAsStateWithLifecycle()
    val snackbarHostState = remember { SnackbarHostState() }
    var showAddDialog by remember { mutableStateOf(false) }
    var selectedSpace by remember { mutableStateOf<StorageSpace?>(null) }
    var showActionSheet by remember { mutableStateOf(false) }
    var spaceToEdit by remember { mutableStateOf<StorageSpace?>(null) }
    var showEditSpaceDialog by remember { mutableStateOf(false) }
    
    // 处理错误消息
    LaunchedEffect(uiState.errorMessage) {
        uiState.errorMessage?.let { message ->
            snackbarHostState.showSnackbar(
                message = message,
                actionLabel = "关闭"
            )
            viewModel.clearErrorMessage()
        }
    }
    
    // 处理成功消息
    LaunchedEffect(uiState.successMessage) {
        uiState.successMessage?.let { message ->
            snackbarHostState.showSnackbar(
                message = message,
                duration = SnackbarDuration.Short
            )
            viewModel.clearSuccessMessage()
        }
    }
    
    // 根据屏幕宽度确定网格列数
    val configuration = LocalConfiguration.current
    val screenWidth = configuration.screenWidthDp.dp
    val columns = if (screenWidth > 600.dp) 3 else 2
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = { 
                    Text(
                        text = stringResource(R.string.app_name),
                        style = MaterialTheme.typography.headlineSmall
                    )
                },
                actions = {
                    IconButton(onClick = onNavigateToSearch) {
                        Icon(
                            imageVector = Icons.Default.Search,
                            contentDescription = "搜索物品"
                        )
                    }
                }
            )
        },
        floatingActionButton = {
            FloatingActionButton(
                onClick = { showAddDialog = true },
                containerColor = MaterialTheme.colorScheme.primaryContainer
            ) {
                Icon(
                    imageVector = Icons.Default.Add,
                    contentDescription = "添加储物空间"
                )
            }
        },
        snackbarHost = {
            ErrorSnackbar(snackbarHostState = snackbarHostState)
        }
    ) { paddingValues ->
        when {
            uiState.isLoading -> {
                LoadingState(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(paddingValues),
                    message = "加载储物空间..."
                )
            }
            
            uiState.storageSpaces.isEmpty() -> {
                EmptyState(
                    title = "还没有储物空间",
                    description = "点击右下角的 + 按钮添加第一个储物空间",
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(paddingValues)
                )
            }
            
            else -> {
                LazyVerticalGrid(
                    columns = GridCells.Fixed(columns),
                    contentPadding = PaddingValues(16.dp),
                    horizontalArrangement = Arrangement.spacedBy(12.dp),
                    verticalArrangement = Arrangement.spacedBy(12.dp),
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(paddingValues)
                ) {
                    items(
                        items = uiState.storageSpaces,
                        key = { it.space.id }
                    ) { spaceWithCount ->
                        val space = spaceWithCount.space.toModel()
                        StorageSpaceCard(
                            space = space,
                            onClick = { 
                                println("DEBUG: MainScreen onClick for space: ${space.name}, id: ${space.id}")
                                onNavigateToStorageDetail(space.id) 
                            },
                            onLongClick = { 
                                println("DEBUG: MainScreen onLongClick for space: ${space.name}")
                                selectedSpace = space
                                showActionSheet = true 
                            },
                            modifier = Modifier
                                .fillMaxWidth()
                                .animateItemPlacement(),
                            itemCount = spaceWithCount.itemCount
                        )
                    }
                }
            }
        }
    }
    
    // 添加储物空间对话框
    if (showAddDialog) {
        AddStorageSpaceDialog(
            onDismiss = { showAddDialog = false },
            onConfirm = { name, description, iconType ->
                viewModel.addStorageSpace(name, description, iconType)
                showAddDialog = false
            }
        )
    }
    
    // 空间删除确认对话框
    if (uiState.spaceToDelete != null && uiState.deleteConfirmationInfo != null) {
        AlertDialog(
            onDismissRequest = { viewModel.cancelSpaceDeletion() },
            title = { 
                Text(
                    text = "确认删除",
                    style = MaterialTheme.typography.headlineSmall
                ) 
            },
            text = { 
                Text(
                    text = uiState.deleteConfirmationInfo!!,
                    style = MaterialTheme.typography.bodyMedium
                ) 
            },
            confirmButton = {
                Button(
                    onClick = { viewModel.confirmSpaceDeletion() },
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.error
                    )
                ) {
                    Text("确认删除")
                }
            },
            dismissButton = {
                TextButton(onClick = { viewModel.cancelSpaceDeletion() }) {
                    Text("取消")
                }
            }
        )
    }
    
    // 长按操作菜单 - 暂时只支持删除
    if (showActionSheet && selectedSpace != null) {
        ActionBottomSheet(
            onDismiss = { 
                showActionSheet = false
                selectedSpace = null
            },
            title = selectedSpace!!.name,
            actions = listOf(
                ActionItem(
                    title = "修改",
                    icon = Icons.Default.Edit,
                    onClick = {
                        spaceToEdit = selectedSpace
                        showEditSpaceDialog = true
                        showActionSheet = false
                        selectedSpace = null
                    }
                ),
                ActionItem(
                    title = "删除",
                    icon = Icons.Default.Delete,
                    onClick = {
                        selectedSpace?.let { space ->
                            viewModel.deleteStorageSpace(space.id)
                        }
                        showActionSheet = false
                        selectedSpace = null
                    },
                    isDestructive = true
                )
            )
        )
    }

    if (showEditSpaceDialog && spaceToEdit != null) {
        AddStorageSpaceDialog(
            onDismiss = { 
                showEditSpaceDialog = false
                spaceToEdit = null
            },
            onConfirm = { name, description, iconType ->
                spaceToEdit?.let { 
                    viewModel.updateSpace(it.id, name, description, iconType) 
                }
                showEditSpaceDialog = false
                spaceToEdit = null
            },
            isEditMode = true,
            initialName = spaceToEdit!!.name,
            initialDescription = spaceToEdit!!.description ?: "",
            initialIconType = spaceToEdit!!.iconType
        )
    }
} 